﻿using IconYuan.Model.DTO.Products;
using Core.Configuration.Api;
using Microsoft.AspNetCore.Mvc;
using IconYuan.Manager.Products;
using SqlSugar;
using Core.Configuration.Config;
using IconYuan.Model.Products;
using IconYuan.Model.DB;
using IconYuan.Model.Entity.Products;
using IconYuan.Api.Services;
using IconYuan.Manager.Markets;
using IconYuan.Model.DTO.Markets;
using IconYuan.Model.Entity.Markets;
using CJiaBao.Core.Utils;
using System;

namespace IconYuan.Api.Controllers.Products
{
    /// <summary>
    /// 商品操作
    /// </summary>
    public class GoodsController : ApiBase
    {
        readonly GoodsManager goodsSvc;
        readonly CateManager cateSvc;
        readonly GoodsImageManager goodsImageSvc;
        readonly SkuManager skuSvc;
        readonly SpecValueManager specValueSvc;

        public GoodsController()
        {
            goodsSvc = new GoodsManager();
            cateSvc = new CateManager();
            goodsImageSvc = new GoodsImageManager();
            skuSvc = new SkuManager();
            specValueSvc = new SpecValueManager();
        }

        /// <summary>
        /// 商品列表(所有)
        /// </summary>
        /// <param name="shop_id">门店id</param>
        /// <param name="categoryId">分类id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<AllGoodsDto> AllList(int shop_id = 0, int categoryId = 0)
        {
            var store_id = GetStoreId();
            var result = new AllGoodsDto();
            //商品分类
            result.cate_list = await cateSvc.GetListAsync(x => x.status == 1 && x.store_id == store_id, "sort asc") ?? new List<Cate>();

            //分类条件搜索
            var cateIds = new List<int>();
            if (categoryId > 0)
            {
                cateIds = result.cate_list.Select(x => x.category_id).ToList();
                cateIds.Add(categoryId);
            }
            else
            {                
                cateIds = result.cate_list.Select(x => x.category_id).ToList();
            }
           
            //商品基础信息
            var goodsList = await goodsSvc.GetAllAsync(shop_id, cateIds);
            var proList = GetPromotionDtoList();
            result.list = GoodsServices.ToGoods(goodsList, proList);
            return result;
        }


        /// <summary>
        /// 商品详情（详细）
        /// </summary>
        /// <param name="goodsId">商品id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<GoodsDetailDto> Detail(int goodsId)
        {
            var goods = await goodsSvc.GetAsync(goodsId);
            if (goods == null) throw new Exception("商品不存在");

            var skuList = await skuSvc.GetListAsync(x => x.goods_id == goods.goods_id);
            var goods_images = await goodsImageSvc.GetListAsync(x => x.goods_id == goods.goods_id, y => y.id, OrderByType.Asc);

            goods_images.ForEach(x => x.image_path = $"{GlobalConfig.CdnDomain}{x.image_path}");

            var detail = new GoodsDetail()
            {
                goods_id = goods.goods_id,
                goods_name = goods.goods_name,
                goods_no = goods.goods_no,
                category_id = goods.category_id,
                goods_price_max = goods.goods_price_max,
                goods_price_min = goods.goods_price_min,
                line_price_max = goods.line_price_max,
                line_price_min = goods.line_price_min,
                is_alone_grade = goods.is_alone_grade,
                is_enable_grade = goods.is_enable_grade,
                is_ind_dealer = goods.is_ind_dealer,
                points = goods.points,
                is_points_gift = goods.is_points_gift,
                stock_total = goods.stock_total,
                sales_actual = goods.sales_actual,
                sales_initial = goods.sales_initial,
                selling_point = goods.selling_point,
                spec_type = goods.spec_type,
                status = goods.status,
                store_id = goods.store_id,
                video = string.Empty,
                videoCover = string.Empty,
                video_cover_id = goods.video_cover_id,
                video_id = goods.video_id,

                is_delete = goods.is_delete,
                content = goods.content,
                create_time = goods.create_time,
                update_time = goods.update_time,
                dealer_money_type = goods.dealer_money_type,
                deduct_stock_type = goods.deduct_stock_type,
                delivery_id = goods.delivery_id,
                first_money = goods.first_money,
                second_money = goods.second_money,
                third_money = goods.third_money,
                goods_image = $"{GlobalConfig.CdnDomain}{goods.goods_image}",
                is_upgrade = GlobalConfig.UpgradeCategoryId.Contains(goods.category_id.ToString()) ? 1 : 0,
                goods_images = goods_images,
            };

            //商品sku
            detail.skuList = skuList.Select(x => new GoodsSkuDto()
            {
                goods_id = x.goods_id,
                goods_price = x.goods_price,
                goods_sku_id = x.goods_sku_id,
                stock_num = x.stock_num

            }).ToList();

            //sku关联的规格id
            var valueIds = new List<object>();
            skuList.Select(x => x.goods_sku_id.Split('_')).ToList().ForEach(ids =>
            {
                valueIds.AddRange(ids);
            });

            //商品规格组
            detail.specList = new List<Spec>();
            var valueList = await specValueSvc.GetByIdsAsync(valueIds.ToArray());
            valueList.ForEach(value =>
            {
                var spec = detail.specList.Find(y => y.spec_id == value.spec_id);
                if (spec == null)
                {
                    spec = new Spec() { spec_id = value.spec_id, spec_name = value.spec_name };
                    spec.value_list = valueList.FindAll(x => x.spec_id == value.spec_id);
                    detail.specList.Add(spec);
                }
            });

            //促销优惠
            var proList = GetPromotionDtoList();
            detail.promotion = proList.Find(y => y.goods_ids== detail.goods_id.ToString());

            return new GoodsDetailDto() { detail = detail };
        }

        /// <summary>
        /// 商品详情（基础）
        /// </summary>
        /// <param name="goodsId">商品id</param>
        /// <returns></returns>
        [HttpGet]
        public GoodsBase Basic(int goodsId)
        {
            return goodsSvc.GetBase<GoodsBase>(goodsId); ;
        }

        private List<PromotionDto> GetPromotionDtoList()
        {
            return DtoHelper.GetPromotionList(GetStoreId()).Select(x =>
             {
                 var pro = new PromotionDto();
                 pro.type = x.type;

                 if (x.type == 1)
                 {
                     var signle = JsonHelper.ToObject<SinglePromotion>(x.ext);
                     pro.type_value = signle.type_value;
                     pro.goods_ids = signle.goods_ids;
                     pro.max_count = signle.max_count;
                     pro.goods_ids = signle.goods_ids;
                 }
                 if (x.type == 2)
                 {
                     var full = JsonHelper.ToObject<FullPromotion>(x.ext);
                     pro.first_cut = full.first_cut;
                     pro.first_limit = full.first_limit;
                     pro.secend_cut = full.secend_cut;
                     pro.secend_limit = full.secend_limit;
                     pro.max_count = full.max_count;
                     pro.goods_ids = full.goods_ids;
                 }
                 return pro;
             }).ToList();
        }
    }
}
